import express, { Request, Response } from "express"

import { useCheckAndResponse } from "../../utils/common"
import { LoggedInRequest } from "../../types"
import { checkError } from "../../utils/token"
import { AddLocationParam, EditLocationParam } from "@Tea/model"
import { LocationCtx } from "../../context/LocationCtx"

const locationRouter = express.Router()

locationRouter.post('/', async (req: LoggedInRequest, res: Response) => {
  try {
    const params = req.body as AddLocationParam

    if (!!params.isDefault) {
      await LocationCtx.getInstance().setNotDetault(req.userInfo.userId)
    }

    const result = await LocationCtx.getInstance().addLocation(params, req.userInfo.userId)

    useCheckAndResponse(res, result[0], '添加成功')
  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg: checkError(ex)
    })
  }
})

locationRouter.get('/', async (req: LoggedInRequest, res: Response) => {
  try {

    const data = await LocationCtx.getInstance().locationList(req.userInfo.userId)

    res.send({
      code: 1,
      msg: "查询成功",
      data
    })
  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg: checkError(ex)
    })
  }
})

locationRouter.put('/', async (req: LoggedInRequest, res: Response) => {
  try {
    const params = req.body as EditLocationParam

    if (!!params.isDefault) {
      await LocationCtx.getInstance().setNotDetault(req.userInfo.userId)
    }

    const result = await LocationCtx.getInstance().editLocation(params, req.userInfo.userId)

    useCheckAndResponse(res, result[0], '修改成功')
  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg: checkError(ex)
    })
  }
})

locationRouter.delete('/', async (req: LoggedInRequest, res: Response) => {
  try {
    const query = req.query as any as { takeOverId: number }

    const result = await LocationCtx.getInstance().deleteLocation(query.takeOverId, req.userInfo.userId)

    useCheckAndResponse(res, result[0], '删除成功')
  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg: checkError(ex)
    })
  }
})

export default locationRouter